package com.obuge.yfly.Interceptor;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.ServletException;

@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler(value = CustomerException.class)
    public ResponseEntity<Object> exception(CustomerException exception) {
        if(exception.isPrint()) exception.printStackTrace();
        return new ResponseEntity<>(ResultData.fail(exception.getErrorCode(),exception.getErrorMsg()), HttpStatus.OK);
    }
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseEntity<Object> exception(RuntimeException exception) {
        exception.printStackTrace();
        return new ResponseEntity<>(ResultData.fail(500,exception.getMessage()), HttpStatus.OK);
    }
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> exception(Exception exception) {
        exception.printStackTrace();
        return new ResponseEntity<>(ResultData.fail(501,exception.getMessage()), HttpStatus.OK);
    }
    @ExceptionHandler(value = NullPointerException.class)
    public ResponseEntity<Object> exception(NullPointerException exception) {
        exception.printStackTrace();
        return new ResponseEntity<>(ResultData.fail(502,exception.getMessage()), HttpStatus.OK);
    }
    @ExceptionHandler(value = ServletException.class)
    public ResponseEntity<Object> exception(ServletException exception) {
        exception.printStackTrace();
        return new ResponseEntity<>(ResultData.fail(503,exception.getMessage()), HttpStatus.OK);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
//        e.printStackTrace();
        return new ResponseEntity<>(ResultData.fail(403,e.getBindingResult().getFieldError().getDefaultMessage()), HttpStatus.OK);
    }
}
